package com.gome.ocean.controller.datasource;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.constants.WebSqlContants;
import com.gome.ocean.common.enums.DataBaseType;
import com.gome.ocean.common.enums.DataSource;
import com.gome.ocean.common.exception.AuthorityManagerException;
import com.gome.ocean.common.utils.DBCharUtils;
import com.gome.ocean.common.utils.DBSecurityUtil;
import com.gome.ocean.common.utils.DBUtil;
import com.gome.ocean.common.utils.FormatUtil;
import com.gome.ocean.common.utils.HttpClientUtil;
import com.gome.ocean.common.utils.JdbcUtils;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.dao.model.datasource.AuthGroupBean;
import com.gome.ocean.dao.model.datasource.DSMDataBean;
import com.gome.ocean.dao.model.datasource.DataSourceAuthorityOAApplyBean;
import com.gome.ocean.dao.model.datasource.DatasourceBO;
import com.gome.ocean.dao.model.datasource.SQLUploadRecordBean;
import com.gome.ocean.dao.model.datasource.TableStructBean;
import com.gome.ocean.dao.model.webservice.Model_Permissions;
import com.gome.ocean.service.base.AuthorityBaseController;
import com.gome.ocean.service.datax.DatasourceService;
import com.gome.ocean.service.datax.IDataSourceAuthApplyService;
import com.gome.ocean.service.datax.ISQLUploadRecordService;
import com.gome.ocean.service.webservice.permission.InterfaceResult;
import com.gome.ocean.service.webservice.permission.PermissionsServiceSoap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Controller
public class SQLDataSourceController extends AuthorityBaseController {

    private static final Logger LOG = LoggerFactory.getLogger(SQLDataSourceController.class);

    private final String FIND_NO_DATASOURCE = "未查询到数据源";

    @Autowired
    private DatasourceService           datasourceService;
    @Autowired
    private PermissionsServiceSoap      permissionsServiceSoap;
    @Autowired
    private IDataSourceAuthApplyService applyService;
    @Autowired
    private ISQLUploadRecordService     isqlUploadRecordService;

    @RequestMapping(value = "/datasource/insert", method = RequestMethod.GET)
    public ModelAndView insertGet(ModelAndView mav) {
        try {
            mav.addObject("projectNames", getProperProjects());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            mav.addObject("errorMsg", "查询项目组列表失败");
        }
        mav.addObject("currentRole", this.getCurrentUserObj().getRole());
        mav.setViewName("datasource/insert");
        return mav;
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/datasource/insert", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage insertPost(HttpServletRequest req) {
        ResponsePage page = getResponsePage();
        String username = req.getParameter("userName");
        String password = req.getParameter("password");
        String project = req.getParameter("project");
        String jdbcurl = req.getParameter("jdbcUrl");
        if (jdbcurl.contains("?")) {
            return page.setErrorMsg("jdbc地址不能带参数");
        }
        DataBaseType dataBaseType = DataBaseType.getDataBaseType(req.getParameter("sourceType"));
        if (StringUtils.isBlank(username)) {
            return page.setErrorMsg("连接串用户名不能为空!");
        }
        if (StringUtils.isBlank(password)) {
            return page.setErrorMsg("连接串密码不能为空!");
        }
        if (StringUtils.isBlank(jdbcurl)) {
            return page.setErrorMsg("连接串不能为空!");
        }
        if (StringUtils.isBlank(project)) {
            return page.setErrorMsg("项目组不能为空");
        }
        if (null == dataBaseType) {
            return page.setErrorMsg("数据库类型未知!");
        }
        DatasourceBO datasourceBO = new DatasourceBO();
        datasourceBO.setUserName(username);
        datasourceBO.setPassword(password);
        datasourceBO.setJdbcUrl(jdbcurl);
        datasourceBO.setProject(project);
        datasourceBO.setSourceType(dataBaseType.getTypeName());
        datasourceBO.setCreateUser(super.getCurrentUser(req));
        datasourceBO.setSourceStatus(DataSource.DATAX.getValue());
        try {
            boolean flag = permitAccess(datasourceBO);
            if (flag) {
                DBUtil.chooseJdbcUrlWithoutRetry(dataBaseType, Arrays.asList(jdbcurl), username, password, null, false);
                if (datasourceService.insertDatasourceBO(datasourceBO)) {
                    return page.setSuccessMsg("数据源创建成功!");
                } else {
                    return page.setErrorMsg("数据源创建失败");
                }
            }
            return page.setErrorMsg("您没有该项目组权限！");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("新建数据源中发生异常，异常信息为：" + ExceptionUtils.getMessage(e));
        }
    }

    @RequestMapping("/datasource/getDSMDatasourceInfo")
    @ResponseBody
    public Map<String, Object> getDSMDatasourceInfo(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        try {
            String envStr = this.getDiffEnvironmentValue();
            String ip = "";
            if (envStr.equals("PRD")) {
                ip = Constants.DSM_LIVE_IP;
                envStr = "live";
            } else {
                ip = Constants.DSM_TEST_IP;
                envStr = envStr.toLowerCase();
            }
            String appName = request.getParameter("appName");
            if (appName == null || StringUtils.isBlank(appName)) {
                map.put("failure", true);
                map.put("success", false);
                map.put("root", "appName不允许为空值");
            }
            HttpClientUtil clientUtil = new HttpClientUtil();
            String path = WebSqlContants.getFormatDSMDatasourcePathStr(ip, appName, envStr);
            URL url = new URL(path);
            HttpGet httpGet = HttpClientUtil.getGetRequest();
            // URI uri = new URI(url.getProtocol(), url.getHost(),
            // url.getPath(), url.getQuery(), null);
            httpGet.setURI(url.toURI());
            String callbackJson = clientUtil.executeAndGetWithFailedRetry(httpGet, 6, 10001);
            if (callbackJson != null && StringUtils.isNotBlank(callbackJson)) {
                List<DSMDataBean> dsmSets = JSON.parseArray(callbackJson, DSMDataBean.class);
                map.put("failure", false);
                map.put("success", true);
                map.put("root", dsmSets);
            } else {
                map.put("failure", true);
                map.put("success", false);
                map.put("root", "该应用名称未查到相应的数据源信息,请核实应用名称或者联系DBA!");
            }
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            map.put("failure", true);
            map.put("success", false);
            map.put("root", "提交失败:" + ExceptionUtils.getMessage(e));
        }
        return map;
    }

    @RequestMapping("/datasource/insertDSMDatasource")
    @ResponseBody
    public Map<String, Object> insertDSMDatasource(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        try {
            String appName = request.getParameter("appName");
            Integer id = Integer.parseInt(request.getParameter("id"));
            String projectName = request.getParameter("projectName");
            if (StringUtils.isBlank(appName) || StringUtils.isBlank(projectName)) {
                map.put("failure", true);
                map.put("success", false);
                map.put("root", "参数错误");
            } else {
                DSMDataBean dsm = new DSMDataBean();
                String envStr = this.getDiffEnvironmentValue();
                String ip = "";
                if (envStr.equals("PRD")) {
                    ip = Constants.DSM_LIVE_IP;
                    envStr = "live";
                } else {
                    ip = Constants.DSM_TEST_IP;
                    envStr = envStr.toLowerCase();
                }
                HttpClientUtil clientUtil = new HttpClientUtil();
                String path = WebSqlContants.getFormatDSMDatasourcePathStr(ip, appName, envStr);
                URL url = new URL(path);
                HttpGet httpGet = HttpClientUtil.getGetRequest();
                httpGet.setURI(url.toURI());
                String callbackJson = clientUtil.executeAndGetWithFailedRetry(httpGet, 6, 10001);
                if (callbackJson != null && StringUtils.isNotBlank(callbackJson)) {
                    List<DSMDataBean> dsmLists = JSON.parseArray(callbackJson, DSMDataBean.class);
                    if (dsmLists != null && dsmLists.size() > 0) {
                        for (DSMDataBean bean : dsmLists) {
                            if (bean.getId().equals(id)) {
                                dsm.setDbIp(bean.getDbIp());
                                dsm.setDbName(bean.getDbName());
                                dsm.setDbPort(bean.getDbPort());
                                dsm.setDbPwd(bean.getDbPwd());
                                dsm.setDbPwdKey(bean.getDbPwdKey());
                                dsm.setDbType(bean.getDbType());
                                dsm.setDbUser(bean.getDbUser());
                                break;
                            }
                        }
                    }
                }
                String jdbcUrl = "";
                if (dsm.getDbType().equalsIgnoreCase(DataBaseType.Oracle.getTypeFullName())) {
                    jdbcUrl = JdbcUtils.getOracleJdbcUrl2(dsm.getDbIp(), dsm.getDbPort().toString(), dsm.getDbUser());
                } else {
                    jdbcUrl = JdbcUtils.getMysqlJdbcUrl(dsm.getDbIp(), dsm.getDbPort().toString(), dsm.getDbName());
                }
                String passWd = DBSecurityUtil.dsmDecrypt(dsm.getDbPwd(), dsm.getDbPwdKey());
                DataBaseType dataBaseType = DataBaseType.getDataBaseType(dsm.getDbType().toLowerCase());
                DatasourceBO datasourceBO = new DatasourceBO();
                datasourceBO.setUserName(dsm.getDbUser());
                datasourceBO.setPassword(passWd);
                datasourceBO.setJdbcUrl(jdbcUrl);
                datasourceBO.setProject(projectName);
                datasourceBO.setSourceType(dataBaseType.getTypeName());
                datasourceBO.setCreateUser(this.getCurrentUser());
                datasourceBO.setSourceStatus(DataSource.DSM.getValue());
                boolean flag = permitAccess(datasourceBO);
                if (flag) {
                    // 校验
                    DatasourceBO dataBean = datasourceService.findDatasourceBOByTypeAndUrl(dataBaseType.getTypeName(),
                        jdbcUrl);
                    if (dataBean != null) {
                        map.put("failure", true);
                        map.put("success", false);
                        map.put("root", "数据源已经存在,无法重复加入,如有疑问,请联系管理员!");
                        return map;
                    }
                    DBUtil.chooseJdbcUrlWithoutRetry(dataBaseType,
                        Arrays.asList(jdbcUrl),
                        dsm.getDbUser(),
                        passWd,
                        null,
                        false);
                    if (datasourceService.insertDatasourceBO(datasourceBO)) {
                        map.put("failure", false);
                        map.put("success", true);
                        map.put("root", "数据源创建成功");
                    } else {
                        map.put("failure", true);
                        map.put("success", false);
                        map.put("root", "数据源创建失败");
                    }
                } else {
                    map.put("failure", true);
                    map.put("success", false);
                    map.put("root", "您没有该项目组权限！无法创建数据源");
                }
            }
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getMessage(e));
            map.put("failure", true);
            map.put("success", false);
            map.put("root", "提交失败:" + ExceptionUtils.getMessage(e));
        }
        return map;
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/datasource/remove", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage remove(@RequestParam("id") long id) {
        ResponsePage page = getResponsePage();
        if (id <= 0) {
            return page.setErrorMsg("id不能小于等于0");
        }
        try {
            DatasourceBO datasourceBO = datasourceService.findDatasourceBOById(id);
            if (null == datasourceBO) {
                return page.setErrorMsg("数据中不存在此条数据源记录");
            }
            if (!isAdmin() && !getCurrentUser().equals(datasourceBO.getCreateUser())) {
                return page.setErrorMsg("您没有删除此条数据源记录的权限，请联系管理员或者数据源的创建者");
            }
            boolean flag = permitAccess(datasourceBO);
            if (flag) {
                if (datasourceService.removeDatasourceBOById(id)) {
                    return page.setSuccessMsg("删除成功");
                } else {
                    return page.setErrorMsg("删除失败");
                }
            }
            return page.setErrorMsg("您没有该项目组权限！");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(EXCEPTION_MSG);
        }
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/datasource/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage updatePost(HttpServletRequest req) {
        ResponsePage page = getResponsePage();
        Long id = Long.parseLong((req.getParameter("id")));
        String username = req.getParameter("userName");
        // String password = req.getParameter("password");
        String jdbcurl = req.getParameter("jdbcUrl");
        DataBaseType dataBaseType = DataBaseType.getDataBaseType(req.getParameter("sourceType"));
        if (null == id || id.intValue() < 0 || dataBaseType == null) {
            return page.setErrorMsg("更新失败!请检查参数!");
        }
        DatasourceBO datasourceBO = datasourceService.findDatasourceBOById(id);
        if (null == datasourceBO) {
            return page.setErrorMsg("更新对象不存在!");
        }

        if (!isAdmin() && !getCurrentUser().equals(datasourceBO.getCreateUser())) {
            return page.setErrorMsg("您没有更新此条数据源记录的权限，请联系管理员或者数据源的创建者");
        }

        if (StringUtils.isNotEmpty(username)) {
            datasourceBO.setUserName(username);
        }
        if (StringUtils.isNotEmpty(jdbcurl)) {
            datasourceBO.setJdbcUrl(jdbcurl);
        }
        datasourceBO.setSourceType(dataBaseType.getTypeName());
        datasourceBO.setUpdateUser(super.getCurrentUser(req));
        try {
            boolean flag = permitAccess(datasourceBO);
            if (flag) {
                DBUtil.chooseJdbcUrlWithoutRetry(dataBaseType,
                    Arrays.asList(jdbcurl),
                    username,
                    datasourceBO.getPassword(),
                    null,
                    false);
                if (datasourceService.updateDatasourceBOById(datasourceBO)) {
                    return page.setSuccessMsg("数据源更新成功!");
                } else {
                    return page.setErrorMsg("数据源更新失败!");
                }
            }
            return page.setErrorMsg("您没有该项目组权限！");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("新建数据源中发生异常，异常信息为：" + ExceptionUtils.getMessage(e));
        }
    }

    @RequestMapping(value = "/datasource/find", method = RequestMethod.GET)
    public String findGet() {
        return "datasource/find";
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/datasource/find", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findPost() {
        ResponsePage response = getResponsePage();
        int pageNum = getPageNum();
        int pageSize = getPageSize();
        try {
            Page<DatasourceBO> datasourceBOs;
            if (isAdmin() || isDBA()) {
                datasourceBOs = datasourceService.findDataSources(pageNum, pageSize);
            } else {
                datasourceBOs = datasourceService.findAllDatasourceBOsByProjectNames(getProperProjects(),
                    pageNum,
                    pageSize);
            }
            if (CollectionUtils.isEmpty(datasourceBOs)) {
                return response.emptyPage(FIND_NO_RESULTS);
            }
            return response.setPage(datasourceBOs, FIND_SUCCESS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(EXCEPTION_MSG);
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/datasource/findAll", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findAll() {
        ResponsePage page = getResponsePage();
        try {
            Page<DatasourceBO> datasourceBOs;
            datasourceBOs = datasourceService.findDataSources(1, 500);
            if (null == datasourceBOs || datasourceBOs.isEmpty()) {
                return page.emptyPage(FIND_NO_RESULTS);
            }
            List<DatasourceBO> filterDataSources = filterDataSources(datasourceBOs);
            if (filterDataSources.isEmpty()) {
                return page.emptyPage(FIND_NO_RESULTS);
            }
            return page.setJustList(filterDataSources, FIND_SUCCESS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(EXCEPTION_MSG);
        }
    }

    /**
     * 对查询出来的DatasourceBO根据项目组进行过滤<br>
     * 利用session缓存projectNames
     * 
     * @param datasourceBOs
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<DatasourceBO> filterDataSources(List<DatasourceBO> datasourceBOs) {
        if (isAdmin()) return datasourceBOs;
        HttpSession session = getHttpRequest().getSession();
        List<String> projectNames = (List<String>) session.getAttribute("projectNames");
        if (projectNames == null) {
            projectNames = getCurrentUserProjects();
            session.setAttribute("projectNames", projectNames);
        }
        List<DatasourceBO> filterDataSources = Lists.newArrayList();
        for (DatasourceBO datasourceBO : datasourceBOs) {
            if (projectNames.contains(datasourceBO.getProject())) {
                filterDataSources.add(datasourceBO);
            }
        }
        return filterDataSources;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/datasource/findById", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findById(long id) {
        ResponsePage<DatasourceBO> response = getResponsePage();
        try {
            DatasourceBO dataSource = datasourceService.findDatasourceBOById(id);
            if (dataSource == null) return response.setErrorMsg(FIND_NO_RESULTS);
            if (permitAccess(dataSource)) {
                return response.setSingleObject(dataSource, FIND_SUCCESS);
            } else {
                return response.setNoAuth();
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(EXCEPTION_MSG);
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/findByType", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findByType(String sourceType) {
        ResponsePage response = getResponsePage();
        try {
            List<DatasourceBO> dataSources;
            if (isAdmin()) {
                dataSources = datasourceService.findDataSourceByType(sourceType);
            } else {
                dataSources = datasourceService.findDataSourcesByProjectNamesAndType(getCurrentUserProjects(),
                    Integer.parseInt(sourceType));
            }
            if (CollectionUtils.isEmpty(dataSources)) {
                return response.emptyPage(FIND_NO_RESULTS);
            }
            return response.setJustList(dataSources, FIND_SUCCESS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(EXCEPTION_MSG);
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/datasource/getTables", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage getTables(long id) {
        ResponsePage<String> response = getResponsePage();
        try {
            DatasourceBO dataSource = datasourceService.findDatasourceBOById(id);
            if (dataSource == null) return response.setErrorMsg(FIND_NO_DATASOURCE);
            if (!permitAccess(dataSource)) return response.setNoAuth();
            List<String> tables = DBUtil.getTables(DataBaseType.getDataBaseType(dataSource.getSourceType()),
                dataSource.getJdbcUrl(),
                dataSource.getUserName(),
                dataSource.getPassword());
            if (CollectionUtils.isEmpty(tables)) return response.emptyPage(FIND_NO_RESULTS);
            return response.setJustList(tables, FIND_SUCCESS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(EXCEPTION_MSG);
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/getTableColumns", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage getTableColumns(long id, String tableName) {
        ResponsePage<String> response = getResponsePage();
        if (StringUtils.isEmpty(tableName)) return response.setErrorMsg("tableName参数不能为空!");
        try {
            DatasourceBO dataSource = datasourceService.findDatasourceBOById(id);
            if (dataSource == null) return response.setErrorMsg(FIND_NO_DATASOURCE);
            if (!permitAccess(dataSource)) return response.setNoAuth();
            List<String> columns = DBUtil.getTableColumns(DataBaseType.getDataBaseType(dataSource.getSourceType()),
                dataSource.getJdbcUrl(),
                dataSource.getUserName(),
                dataSource.getPassword(),
                tableName);
            if (CollectionUtils.isEmpty(columns)) return response.emptyPage(FIND_NO_RESULTS);
            return response.setJustList(columns, FIND_SUCCESS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(EXCEPTION_MSG);
        }
    }

    @RequestMapping("/datasource/applyDatasourceAuthority")
    public ModelAndView applyDatasourceAuthority(HttpServletRequest request, ModelAndView mav) {
        mav.addObject("ipValue", this.getDBAInterfaceIp());
        mav.addObject("envirValue", this.getDiffEnvironmentValue());
        HttpClientUtil httpClientUtil = new HttpClientUtil();

        String authGroupPath = WebSqlContants.getFormatAuthorityGroupPathStr(this.getDBAInterfaceIp(),
            "{\"ptype\":\"group_list\"}");
        try {
            HttpGet httpGet = HttpClientUtil.getGetRequest();
            URL urlAuth = new URL(authGroupPath);
            URI uri = new URI(urlAuth.getProtocol(), urlAuth.getHost(), urlAuth.getPath(), urlAuth.getQuery(), null);
            httpGet.setURI(uri);
            String authJson = httpClientUtil.executeAndGetWithFailedRetry(httpGet, 6, 10001);
            List<AuthGroupBean> authLists = JSONArray.parseArray(authJson, AuthGroupBean.class);
            mav.addObject("authLists", authLists);
            List<String> projectLists = this.getCurrentUserProjects();
            mav.addObject("projectLists", projectLists);
        } catch (MalformedURLException | URISyntaxException e) {
            LOG.error(e.getMessage(), e);
        }
        mav.addObject("errorMsg", false);
        mav.setViewName("datasource/apply_datasource");
        return mav;
    }

    @RequestMapping("/datasource/getTableByAdmin")
    @ResponseBody
    public Map<String, Object> getTableByAdmin(HttpServletRequest request, String adId) {
        Map<String, Object> resultMap = Maps.newHashMap();
        if (StringUtils.isEmpty(adId)) {
            resultMap.put("failure", true);
            resultMap.put("root", "参数错误！请检查!");
            return resultMap;
        }
        try {
            List<String> tables;
            DataBaseType dataBaseType = DataBaseType.getDataBaseType("3");
            String jdbc = null;
            if (DataBaseType.Oracle == dataBaseType) {
                jdbc = JdbcUtils.getOracleJdbcUrl(this.getDBAInterfaceIp(),
                    WebSqlContants.CONMMON_PORT,
                    WebSqlContants.COMMON_DBNAME);
                Connection conn = DBUtil.getConnection(dataBaseType,
                    jdbc,
                    WebSqlContants.GLOBLE_USER,
                    WebSqlContants.GLOBLE_PWD);
                tables = DBUtil.getTablesByConnAdmin(dataBaseType, conn, Long.parseLong(adId));
            } else {
                resultMap.put("failure", true);
                resultMap.put("root", "不支持数据源类型!");
                return resultMap;
            }
            resultMap.put("success", true);
            resultMap.put("root", DBCharUtils.sort(tables));
            return resultMap;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultMap.put("failure", true);
            resultMap.put("root", e.getMessage());
            return resultMap;
        }
    }

    @RequestMapping("/datasource/commitFormDatasource")
    @ResponseBody
    public Map<String, Object> commitFormDatasource(HttpServletRequest request) {
        Map<String, Object> resultMap = Maps.newHashMap();
        try {
            DataSourceAuthorityOAApplyBean applyBean = new DataSourceAuthorityOAApplyBean();
            // common data
            String userName_ZN = request.getParameter("userName");
            applyBean.setApplyUser(userName_ZN);
            String remark = request.getParameter("remark");
            if (StringUtils.isBlank(remark)) {
                remark = "申请";
            }
            applyBean.setRemark(remark);
            String usage = request.getParameter("usgae");
            applyBean.setUsgae(usage);
            User user = this.getCurrentUserObj();
            applyBean.setEmail(user.getEmail());
            applyBean.setAccountNum(user.getEmail().split("@")[0]);
            applyBean.setStatus(0);
            if (StringUtils.isEmpty(this.getDepartMentByAccount(applyBean.getAccountNum()))) {
                resultMap.put("failure", true);
                resultMap.put("msg",
                    "提交数据失败，您当前登录的账户(" + applyBean.getEmail() + ")在OA系统中不存在,请确定登录的账户地址为正确邮件地址! \n如不理解,请联系管理员。");
                return resultMap;
            }
            applyBean.setDepartment(this.getDepartMentByAccount(applyBean.getAccountNum()));
            String formType = request.getParameter("formType");
            applyBean.setFormType(Integer.parseInt(formType));
            String dbName = request.getParameter("dbName");
            String dbid = request.getParameter("dbid");
            if (StringUtils.isNotEmpty(dbName) && StringUtils.isNotEmpty(dbid)) {
                applyBean.setDbName(dbName);
                applyBean.setAdid(Long.parseLong(dbid));
            }
            String deadline = request.getParameter("deadLine");
            if (StringUtils.isNotEmpty(deadline)) {
                SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date date = formate.parse(deadline);
                    applyBean.setDeadline(date);
                } catch (ParseException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
            String memberStr = request.getParameter("devApplyMember");
            if (StringUtils.isNotBlank(memberStr)) {
                List<Map<String, Object>> memLists = Lists.newArrayList();
                String[] memArray = memberStr.split(Constants.REG_CN_OR_EN_COMMA);
                for (String str : memArray) {
                    if (StringUtils.isEmpty(this.getDepartMentByAccount(str.split("@")[0]))) {
                        resultMap.put("failure", true);
                        resultMap.put("msg",
                            "提交数据失败，您当前输入的成员账户(" + str + ")在OA系统中不存在,请确定成员的账户地址为正确邮件地址! \n如不理解,请联系管理员");
                        return resultMap;
                    }
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("email", str);
                    map.put("edept", applyBean.getDepartment());
                    memLists.add(map);
                }

                String jsonMember = JSON.toJSONString(memLists);
                applyBean.setMember(jsonMember);
            }
            String tableJson = request.getParameter("tableStructJson");
            if (StringUtils.isNotBlank(tableJson)) {
                List<TableStructBean> lists = JSONArray.parseArray(tableJson, TableStructBean.class);
                for (TableStructBean table : lists) {
                    if (table.getI() == null) table.setI("N");
                    if (table.getD() == null) table.setD("N");
                    if (table.getU() == null) table.setU("N");
                    if (table.getS() == null) table.setS("N");
                }
                String json = JSON.toJSONString(lists);
                applyBean.setTableStructJson(json);
            }
            applyBean.setDepartMag(user.getEmail().split("@")[0]);
            String gid = request.getParameter("gid");
            String gname = request.getParameter("gname");
            if (StringUtils.isNotEmpty(gid) && StringUtils.isNotEmpty(gname)) {
                applyBean.setGid(Long.parseLong(gid));
                applyBean.setAuthGroup(gname);
            }
            String serverIpAddr = request.getParameter("serverIpAddr");
            if (StringUtils.isNotBlank(serverIpAddr)) {
                List<String> servList = Lists.newArrayList();
                if (serverIpAddr.contains(Constants.REG_CN_OR_EN_COMMA)) {
                    for (String str : serverIpAddr.split(Constants.REG_CN_OR_EN_COMMA)) {
                        servList.add(str);
                    }
                } else {
                    servList.add(serverIpAddr);
                }
                applyBean.setServiceIpAddr(JSON.toJSONString(servList));
            }
            String appName = request.getParameter("appName");
            String appId = request.getParameter("appId");
            if (StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(appName)) {
                applyBean.setAppName(appName);
                applyBean.setApId(Long.parseLong(appId));
            }
            String projectName = request.getParameter("project");
            if (StringUtils.isEmpty(projectName)) {
                resultMap.put("failure", true);
                resultMap.put("msg", "失败");
                return resultMap;
            }
            applyBean.setProject(projectName);
            applyBean.setDbaAuthMag("zhangqian@gomeplus.com");
            applyBean.setOperatMag("liyongbin@gomeplus.com");
            applyBean.setCto("wangzengzhi@gomeplus.com");
            boolean isPermission = super.permitAccess(applyBean);
            if (isPermission) {
                applyBean.setCreateTime(new Date());
                boolean flag = applyService.insert(applyBean);
                if (flag) {
                    resultMap.put("success", true);
                    resultMap.put("msg", "提交成功");
                    return resultMap;
                } else {
                    resultMap.put("failure", true);
                    resultMap.put("msg", "提交数据失败，请检查字段是否符合规则");
                    return resultMap;
                }
            }
            resultMap.put("failure", true);
            resultMap.put("msg", "提交失败，您没有该项目组权限");
            return resultMap;
        } catch (NumberFormatException | AuthorityManagerException | RemoteException e) {
            LOG.error(e.getMessage(), e);
            resultMap.put("failure", true);
            resultMap.put("msg", "提交失败，异常信息: \n" + ExceptionUtils.getMessage(e));
            return resultMap;

        }

    }

    @RequestMapping("/datasource/ajaxCommitOaInterface")
    @ResponseBody
    public Map<String, Object> ajaxCommitOaInterface(HttpServletRequest request, String oaMId) throws RemoteException {
        Map<String, Object> resultMap = Maps.newHashMap();
        try {
            Long oaMid = Long.parseLong(oaMId);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", oaMid);
            DataSourceAuthorityOAApplyBean oaApplyBean = applyService.getBeanByMap(map);
            if (oaApplyBean != null) {
                Map<String, Object> commitMap = new HashMap<String, Object>();
                // common params
                commitMap.put("ptype", WebSqlContants.GROUP_APPLY);
                commitMap.put("email", oaApplyBean.getEmail());
                commitMap.put("edept", oaApplyBean.getDepartment());
                StringBuilder sb = new StringBuilder();
                sb.append(oaApplyBean.getDepartMag())
                    .append(",")
                    .append("zhangqian@gomeplus.com")
                    .append(",")
                    .append("liyongbin@gomeplus.com")
                    .append(",")
                    .append("wangzengzhi@gomeplus.com");
                commitMap.put("auser", sb.toString());
                commitMap.put("atime", new Date());
                commitMap.put("astatus", oaApplyBean.getStatus());
                commitMap.put("sn", this.getDiffEnvironmentValue().concat("-") + oaApplyBean.getId());
                InterfaceResult result = new InterfaceResult();
                if (oaApplyBean.getFormType().equals(1)) {
                    commitMap.put("adid", oaApplyBean.getAdid());
                    commitMap.put("privilege", oaApplyBean.getTableStructJson());
                    commitMap.put("usage", oaApplyBean.getRemark());
                    commitMap.put("member", oaApplyBean.getMember());
                    commitMap.put("apply_type", "dev");
                    String jsonParam = JSON.toJSONString(commitMap);
                    Map<String, Object> callMap = this.executeHttp(oaMId, this.getDBAInterfaceIp(), jsonParam);

                    Model_Permissions devApplyPerm = new Model_Permissions();
                    devApplyPerm.setId(oaMid.toString());
                    devApplyPerm.setFormType("1");
                    devApplyPerm.setAccountNum(oaApplyBean.getAccountNum());
                    devApplyPerm.setApplyUser(oaApplyBean.getApplyUser());
                    devApplyPerm.setEmail(oaApplyBean.getEmail());
                    devApplyPerm.setDepartment(oaApplyBean.getDepartment());
                    devApplyPerm.setMember(oaApplyBean.getMember());
                    devApplyPerm.setDbName(oaApplyBean.getDbName());
                    devApplyPerm.setTableStructJson(oaApplyBean.getTableStructJson());
                    devApplyPerm.setDeadline(FormatUtil.fromMilliseconds2String(oaApplyBean.getDeadline().getTime()));
                    devApplyPerm.setAuthPurpose(oaApplyBean.getUsgae());
                    devApplyPerm.setRemark(oaApplyBean.getRemark());
                    devApplyPerm.setDepartMag(oaApplyBean.getDepartMag());
                    devApplyPerm.setAppName("");
                    devApplyPerm.setServiceIpAddr("");
                    devApplyPerm.setAuthGroup("");
                    devApplyPerm.setExportSql("");

                    if (callMap.get("state").equals("success")) {
                        result = permissionsServiceSoap.tranDataToOA(devApplyPerm);
                    } else {
                        resultMap.put("success", false);
                        resultMap.put("msg", "OA提交失败," + callMap.get("info").toString());
                        return resultMap;
                    }

                } else if (oaApplyBean.getFormType().equals(3)) {
                    commitMap.put("gid", oaApplyBean.getGid());
                    commitMap.put("adid", oaApplyBean.getAdid());
                    commitMap.put("privilege", oaApplyBean.getTableStructJson());
                    commitMap.put("apply_type", "dev-add");
                    String jsonParam = JSON.toJSONString(commitMap);
                    Map<String, Object> callMap = this.executeHttp(oaMId, this.getDBAInterfaceIp(), jsonParam);

                    Model_Permissions devAddPerm = new Model_Permissions();
                    devAddPerm.setId(oaMid.toString());
                    devAddPerm.setFormType("3");
                    devAddPerm.setApplyUser(oaApplyBean.getApplyUser());
                    devAddPerm.setAccountNum(oaApplyBean.getAccountNum());
                    devAddPerm.setEmail(oaApplyBean.getEmail());
                    devAddPerm.setDepartment(oaApplyBean.getDepartment());
                    devAddPerm.setAuthGroup(oaApplyBean.getAuthGroup());
                    devAddPerm.setDbName(oaApplyBean.getDbName());
                    devAddPerm.setTableStructJson(oaApplyBean.getTableStructJson());
                    devAddPerm.setAuthPurpose(oaApplyBean.getUsgae());
                    devAddPerm.setRemark(oaApplyBean.getRemark());
                    devAddPerm.setDepartMag(oaApplyBean.getDepartMag());
                    devAddPerm.setAppName("");
                    devAddPerm.setDeadline("");
                    devAddPerm.setMember("");
                    devAddPerm.setServiceIpAddr("");
                    devAddPerm.setExportSql("");
                    if (callMap.get("state").equals("success")) {
                        result = permissionsServiceSoap.tranDataToOA(devAddPerm);
                    } else {
                        resultMap.put("success", false);
                        resultMap.put("msg", "OA提交失败," + callMap.get("info").toString());
                        return resultMap;
                    }

                } else if (oaApplyBean.getFormType().equals(5)) {
                    commitMap.put("gid", oaApplyBean.getGid());
                    commitMap.put("member", oaApplyBean.getMember());
                    commitMap.put("apply_type", "dev-add-group");
                    String jsonParam = JSON.toJSONString(commitMap);
                    Map<String, Object> callMap = this.executeHttp(oaMId, this.getDBAInterfaceIp(), jsonParam);

                    Model_Permissions devAddAuthGpPerm = new Model_Permissions();
                    devAddAuthGpPerm.setId(oaMid.toString());
                    devAddAuthGpPerm.setFormType("5");
                    devAddAuthGpPerm.setApplyUser(oaApplyBean.getApplyUser());
                    devAddAuthGpPerm.setAccountNum(oaApplyBean.getAccountNum());
                    devAddAuthGpPerm.setEmail(oaApplyBean.getEmail());
                    devAddAuthGpPerm.setDepartment(oaApplyBean.getDepartment());
                    devAddAuthGpPerm.setMember(oaApplyBean.getMember());
                    devAddAuthGpPerm.setAuthGroup(oaApplyBean.getAuthGroup());
                    devAddAuthGpPerm.setAuthPurpose(oaApplyBean.getUsgae());
                    devAddAuthGpPerm.setRemark(oaApplyBean.getRemark());
                    devAddAuthGpPerm.setDepartMag(oaApplyBean.getDepartMag());
                    devAddAuthGpPerm.setAppName("");
                    devAddAuthGpPerm.setDbName("");
                    devAddAuthGpPerm.setDeadline("");
                    devAddAuthGpPerm.setServiceIpAddr("");
                    devAddAuthGpPerm.setTableStructJson("");
                    devAddAuthGpPerm.setExportSql("");

                    if (callMap.get("state").equals("success")) {
                        result = permissionsServiceSoap.tranDataToOA(devAddAuthGpPerm);
                    } else {
                        resultMap.put("success", false);
                        resultMap.put("msg", "OA提交失败," + callMap.get("info").toString());
                        return resultMap;
                    }

                } else if (oaApplyBean.getFormType().equals(7)) {
                    commitMap.put("app_name", oaApplyBean.getAppName());
                    commitMap.put("app_addr", oaApplyBean.getServiceIpAddr());
                    commitMap.put("adid", oaApplyBean.getAdid());
                    commitMap.put("privilege", oaApplyBean.getTableStructJson());
                    commitMap.put("usage", oaApplyBean.getRemark());
                    commitMap.put("apply_type", "app");
                    String jsonParam = JSON.toJSONString(commitMap);
                    Map<String, Object> callMap = this.executeHttp(oaMId, this.getDBAInterfaceIp(), jsonParam);

                    Model_Permissions appApplyPerm = new Model_Permissions();
                    appApplyPerm.setId(oaMid.toString());
                    appApplyPerm.setFormType("7");
                    appApplyPerm.setApplyUser(oaApplyBean.getApplyUser());
                    appApplyPerm.setAccountNum(oaApplyBean.getAccountNum());
                    appApplyPerm.setEmail(oaApplyBean.getEmail());
                    appApplyPerm.setDepartment(oaApplyBean.getDepartment());
                    appApplyPerm.setServiceIpAddr(oaApplyBean.getServiceIpAddr());
                    appApplyPerm.setAppName(oaApplyBean.getAppName());
                    appApplyPerm.setDbName(oaApplyBean.getDbName());
                    appApplyPerm.setTableStructJson(oaApplyBean.getTableStructJson());
                    appApplyPerm.setAuthPurpose(oaApplyBean.getUsgae());
                    appApplyPerm.setRemark(oaApplyBean.getRemark());
                    appApplyPerm.setDepartMag(oaApplyBean.getDepartMag());
                    appApplyPerm.setAuthGroup("");
                    appApplyPerm.setDeadline("");
                    appApplyPerm.setMember("");
                    appApplyPerm.setExportSql("");

                    if (callMap.get("state").equals("success")) {
                        result = permissionsServiceSoap.tranDataToOA(appApplyPerm);
                    } else {
                        resultMap.put("success", false);
                        resultMap.put("msg", "OA提交失败," + callMap.get("info").toString());
                        return resultMap;
                    }

                } else if (oaApplyBean.getFormType().equals(9)) {
                    commitMap.put("app_name", oaApplyBean.getAppName());
                    commitMap.put("adid", oaApplyBean.getAdid());
                    commitMap.put("privilege", oaApplyBean.getTableStructJson());
                    commitMap.put("apply_type", "app-add");
                    String jsonParam = JSON.toJSONString(commitMap);
                    Map<String, Object> callMap = this.executeHttp(oaMId, this.getDBAInterfaceIp(), jsonParam);

                    Model_Permissions appSuperAddPerm = new Model_Permissions();
                    appSuperAddPerm.setId(oaMid.toString());
                    appSuperAddPerm.setFormType("9");
                    appSuperAddPerm.setApplyUser(oaApplyBean.getApplyUser());
                    appSuperAddPerm.setAccountNum(oaApplyBean.getAccountNum());
                    appSuperAddPerm.setEmail(oaApplyBean.getEmail());
                    appSuperAddPerm.setDepartment(oaApplyBean.getDepartment());
                    appSuperAddPerm.setAppName(oaApplyBean.getAppName());
                    appSuperAddPerm.setDbName(oaApplyBean.getDbName());
                    appSuperAddPerm.setTableStructJson(oaApplyBean.getTableStructJson());
                    appSuperAddPerm.setAuthPurpose(oaApplyBean.getUsgae());
                    appSuperAddPerm.setRemark(oaApplyBean.getRemark());
                    appSuperAddPerm.setDepartMag(oaApplyBean.getDepartMag());
                    appSuperAddPerm.setAuthGroup("");
                    appSuperAddPerm.setDeadline("");
                    appSuperAddPerm.setMember("");
                    appSuperAddPerm.setServiceIpAddr("");
                    appSuperAddPerm.setExportSql("");

                    if (callMap.get("state").equals("success")) {
                        result = permissionsServiceSoap.tranDataToOA(appSuperAddPerm);
                    } else {
                        resultMap.put("success", false);
                        resultMap.put("msg", "OA提交失败," + callMap.get("info").toString());
                        return resultMap;
                    }

                } else if (oaApplyBean.getFormType().equals(11)) {
                    commitMap.put("app_name", oaApplyBean.getAppName());
                    commitMap.put("app_addr", oaApplyBean.getServiceIpAddr());
                    commitMap.put("adid", oaApplyBean.getAdid());
                    commitMap.put("apply_type", "app-add-addr");
                    String jsonParam = JSON.toJSONString(commitMap);
                    Map<String, Object> callMap = this.executeHttp(oaMId, this.getDBAInterfaceIp(), jsonParam);

                    Model_Permissions appSuperAddServPerm = new Model_Permissions();
                    appSuperAddServPerm.setId(oaMid.toString());
                    appSuperAddServPerm.setFormType("11");
                    appSuperAddServPerm.setApplyUser(oaApplyBean.getApplyUser());
                    appSuperAddServPerm.setAccountNum(oaApplyBean.getAccountNum());
                    appSuperAddServPerm.setEmail(oaApplyBean.getEmail());
                    appSuperAddServPerm.setDepartment(oaApplyBean.getDepartment());
                    appSuperAddServPerm.setAppName(oaApplyBean.getAppName());
                    appSuperAddServPerm.setDbName(oaApplyBean.getDbName());
                    appSuperAddServPerm.setServiceIpAddr(oaApplyBean.getServiceIpAddr());
                    appSuperAddServPerm.setAuthPurpose(oaApplyBean.getUsgae());
                    appSuperAddServPerm.setRemark(oaApplyBean.getRemark());
                    appSuperAddServPerm.setDepartMag(oaApplyBean.getDepartMag());
                    appSuperAddServPerm.setAuthGroup("");
                    appSuperAddServPerm.setDeadline("");
                    appSuperAddServPerm.setMember("");
                    appSuperAddServPerm.setTableStructJson("");
                    appSuperAddServPerm.setExportSql("");

                    if (callMap.get("state").equals("success")) {
                        result = permissionsServiceSoap.tranDataToOA(appSuperAddServPerm);
                    } else {
                        resultMap.put("success", false);
                        resultMap.put("msg", "OA提交失败," + callMap.get("info").toString());
                        return resultMap;
                    }

                }
                if (result.isIsSuccess()) {
                    oaApplyBean.setStatus(2);
                    oaApplyBean.setUpdateTime(new Date());
                    applyService.updateById(oaApplyBean);
                    SQLUploadRecordBean sqlBean = new SQLUploadRecordBean();
                    sqlBean.setCreateTime(new Date());
                    sqlBean.setDealTime(new Date());
                    sqlBean.setCheckTime(new Date());
                    sqlBean.setDealStatus(WebSqlContants.STATUS_16);
                    sqlBean.setDbaMsg("已提交DBA人员执行,请等待！");
                    sqlBean.setOaDatasourceId(Long.parseLong(oaMId));
                    sqlBean.setCheckStatus(WebSqlContants.STATUS_2);
                    sqlBean.setCheckMsg("已提交申请人OA系统,请到OA中填写审批流程负责人！");
                    isqlUploadRecordService.insertBean(sqlBean);
                }
                resultMap.put("success", result.isIsSuccess());
                resultMap.put("msg", result.getFaultMsg());
                return resultMap;
            }

            resultMap.put("success", false);
            resultMap.put("msg", "表单提交失败,请联系管理员");
            return resultMap;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultMap.put("success", false);
            resultMap.put("msg", ExceptionUtils.getMessage(e));
            return resultMap;
        }
    }

    private Map<String, Object> executeHttp(String mainId, String ip, String jsonParam) {
        Map<String, Object> returnMap = Maps.newHashMap();
        HttpClientUtil clientUtil = new HttpClientUtil();
        String path = WebSqlContants.getFormatAuthorityGroupPathStr(ip, jsonParam);
        SQLUploadRecordBean sqlBean = new SQLUploadRecordBean();
        sqlBean.setCreateTime(new Date());
        sqlBean.setDealTime(new Date());
        sqlBean.setOaDatasourceId(Long.parseLong(mainId));
        try {
            URL url = new URL(path);
            HttpGet httpGet = HttpClientUtil.getGetRequest();
            URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
            httpGet.setURI(uri);
            String callbackJson = clientUtil.executeAndGetWithFailedRetry(httpGet, 6, 10001);
            JSONArray array = JSONArray.parseArray(callbackJson);
            if (array.getString(0).equals("ok")) {
                sqlBean.setCheckStatus(WebSqlContants.STATUS_2);
                sqlBean.setCheckMsg("审核批准后,DBA才将执行");
                sqlBean.setDealStatus(WebSqlContants.STATUS_16);
                sqlBean.setDbaMsg("已提交DBA人员执行,请等待！");
                returnMap.put("state", "success");
                returnMap.put("info", "ok");
            } else {
                sqlBean.setDealStatus(WebSqlContants.STATUS_128);
                sqlBean.setDbaMsg("id=" + mainId + " DBA执行接口异常，请联系管理员！");
                sqlBean.setOaMsg(array.getString(1));
                returnMap.put("state", "failure");
                returnMap.put("info", "id=" + mainId + " DBA执行接口异常，请联系管理员！\r\n" + array.getString(1));
            }
        } catch (Exception e) {
            sqlBean.setDealStatus(WebSqlContants.STATUS_128);
            sqlBean.setDbaMsg("DBA执行接口异常，请联系管理员！");
            returnMap.put("success", false);
            returnMap.put("info", "id=" + mainId + " DBA执行接口异常，请联系管理员！异常信息:\n" + ExceptionUtils.getMessage(e));
            LOG.error(ExceptionUtils.getMessage(e));
        }
        isqlUploadRecordService.insertBean(sqlBean);
        return returnMap;
    }

    @RequestMapping(value = "/datasource/datasourceAuthorityFind", method = RequestMethod.GET)
    public ModelAndView inFindDataAapplyPage(ModelAndView mav) {
        mav.setViewName("datasource/app_datasource_find");
        return mav;
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/datasource/findDataApplyPage", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findDataApplyPage(HttpServletRequest request) {
        ResponsePage<DataSourceAuthorityOAApplyBean> responPage = new ResponsePage<DataSourceAuthorityOAApplyBean>();
        try {
            Integer pageNum = super.getPageNum();
            Integer pageSize = super.getPageSize();
            if (isAdmin() || isDBA()) {
                Page<DataSourceAuthorityOAApplyBean> page = applyService.getBeanAllLists(pageNum, pageSize);
                return responPage.setPage(page, "查询成功");
            } else {
                List<String> projects = super.getCurrentUserProjects();
                if (projects != null && projects.size() > 0) {
                    Page<DataSourceAuthorityOAApplyBean> page = applyService.getBeanListsByProjectGroup(projects,
                        pageNum,
                        pageSize);
                    return responPage.setPage(page, "查询成功");
                } else {
                    responPage.setErrorMsg("请申请加入某个项目组");
                    return responPage;
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return responPage.setErrorMsg(ERROR_MSG);
        }
    }

    @SuppressWarnings({ "rawtypes" })
    @RequestMapping(value = "/datasource/removeApplyDataSource", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage removeApplyDataSource(HttpServletRequest request) {
        ResponsePage page = new ResponsePage();
        Long id = Long.parseLong(request.getParameter("id"));
        try {
            boolean flag = applyService.deleteDatasourceById(id);
            if (flag) {
                return page.setSuccessMsg("删除成功");
            } else {
                return page.setErrorMsg("删除失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("删除失败");
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/datasource/findAppDatasourceById", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findAppDatasourceById(HttpServletRequest request) {
        ResponsePage page = new ResponsePage();
        Long id = Long.parseLong(request.getParameter("id"));
        Map<String, Object> map = Maps.newHashMap();
        map.put("id", id);
        try {
            DataSourceAuthorityOAApplyBean dataBean = applyService.getBeanByMap(map);
            return page.setSingleObject(dataBean, "查询成功");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("查询失败");
        }
    }

    @RequestMapping("/datasource/findOAStatusCheckProgress")
    @ResponseBody
    public Map<String, Object> findOAStatusCheckProgress(HttpServletRequest request) {
        Map<String, Object> map = Maps.newHashMap();
        Long oaId = Long.parseLong(request.getParameter("oaId"));
        List<SQLUploadRecordBean> sqlRecordLists = isqlUploadRecordService.getBeanListByOaId(oaId);
        if (sqlRecordLists != null && sqlRecordLists.size() > 0) {
            map.put("sqlRecordLists", sqlRecordLists);
            map.put("success", true);
            map.put("msg", "查询成功");
            return map;
        }
        map.put("failure", true);
        map.put("msg", "查询失败,暂时没有进度");
        return map;
    }

}
